package admin

import (
	"fmt"
	"net/http"
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/service/admin/fileservice"
	errcodeEnum "yunj/pkg/yunj/core/enum/errcode"
	"yunj/pkg/yunj/core/response"
	"yunj/pkg/yunj/util"

	jsoniter "github.com/json-iterator/go"

	"github.com/gin-gonic/gin"
)

type Other struct {
	Controller
}

// 空请求
func (ctrl *Other) Empty(c *gin.Context) {
	if util.IsAsync(c) {
		response.Success(c, nil)
	}
}

// 提示
func (ctrl *Other) Tips(c *gin.Context) {
	params := util.QueryParams(c)
	// 获取 code
	code, exists := params["code"]
	if !exists {
		code = errcodeEnum.ERROR
	}
	codeValue, ok := errcodeEnum.IsValue(code)
	if !ok {
		codeValue = errcodeEnum.ERROR
	}
	codeEnum := errcodeEnum.ByValue(codeValue)
	// 获取 msg
	msg, exists := params["msg"]
	if !exists {
		msg = codeEnum.GetMsg()
	}
	msgRes, ok := msg.(string)
	if !ok || msgRes == "" {
		msgRes = codeEnum.GetMsg()
	}
	if codeEnum.Value == 200 {
		msgRes += "当前时间：" + time.Now().Format("2006-01-02 15:04:05")
	}

	data := map[string]interface{}{
		"code":   codeEnum.Value,
		"msg":    msgRes,
		"action": codeEnum.GetTipsAction(),
	}
	ctrl.Render(c, "other/tips", data)
}

// 图片验证码
func (ctrl *Other) Captcha(c *gin.Context) {
	hash, imgBase64, err := global.Captcha.Generate()
	if err != nil {
		response.Fail(c, fmt.Sprintf("验证码生成失败！%v", err))
		return
	}
	response.Success(c, map[string]any{
		"hash":    hash,
		"content": imgBase64,
	})
}

// 文件上传
func (ctrl *Other) FileUpload(ctx *gin.Context) {
	responseData := fileservice.File.Upload(ctx)

	json := jsoniter.ConfigCompatibleWithStandardLibrary
	jsonData, err := json.Marshal(responseData)
	if err != nil {
		failJsonData := response.FailJsonData("响应异常！json序列化数据失败：" + err.Error())
		ctx.JSON(http.StatusOK, failJsonData)
		return
	}
	ctx.Data(http.StatusOK, "application/json; charset=utf-8", jsonData)
}
